import { reqlogin } from "../../http/api"
import { Toast } from "antd-mobile"
//state
const initState = {
    // 1.1 初始化user 
    user: {
        phone: "",
        password: ""
    },
    // 2.1 初始化用户信息 userInfo 
    userInfo: sessionStorage.getItem("userInfo") ? JSON.parse(sessionStorage.getItem("userInfo")) : {}
}

//action type
const TYPES = {
    // 1.2 修改user type 
    LOGIN_CHANGE_USER: "LOGIN_CHANGE_USER",
    // 2.2  userInfo type 
    LOGIN_CHANGE_USER_INFO: "LOGIN_CHANGE_USER_INFO"
}

//reducer
const reducer = (state = initState, action) => {
    switch (action.type) {
        //1.3 修改user  {type:"xx",key:"phone",value:"12"}
        case TYPES.LOGIN_CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
        //2.3 userInfo  action ={type:"LOGIN_CHANGE_USER_INFO",userInfo:{token:''}}
        case TYPES.LOGIN_CHANGE_USER_INFO:
            return {
                ...state,
                userInfo: action.userInfo
            }
        default:
            return state;
    }
}

//action creator
export const actions = {
    // 1.4 修改user action 
    changeUser: (key, value) => ({ type: TYPES.LOGIN_CHANGE_USER, key, value }),
    // 2.4 修改 userInfo action 
    changeUserInfo: userInfo => {
        if (userInfo.token) {
            sessionStorage.setItem("userInfo", JSON.stringify(userInfo))
        } else {
            sessionStorage.removeItem("userInfo")
        }
        return { type: TYPES.LOGIN_CHANGE_USER_INFO, userInfo: userInfo }
    },
    // 1.5 登录的逻辑
    doLogin: (push) => {
        return (dispatch, getState) => {
            reqlogin(getUser(getState())).then(res => {
                if (res.data.code == 200) {
                    //弹成功
                    Toast.show({
                        content: res.data.msg
                    })
                    // 存用户信息 res.data.list
                    dispatch(actions.changeUserInfo(res.data.list))

                    //跳转页面
                    push("/index/home")
                }
            })
        }
    }
}

//selector导出数据给组件
// 1.5导出user 
export const getUser = state => state.login.user;
// 2.5导出 userInfo
export const getUserInfo = state => state.login.userInfo;

//导出reducer
export default reducer;